/* eslint-disable vue/attributes-order */
<template>
  <!-- 角色管理 -->
  <div class="app-container">
    <div class="form-container">
      <el-form ref="queryForm" :model="filters" :inline="true" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="filters.roleName"
            size="small"
            clearable
          />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="filters.roleKey"
            size="small"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-select v-model="filters.status" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </el-form-item>
      </el-form>
    </div>

    <div class="btns-group">
      <systemBtns :single="single" has-permi="role" />
      <el-button
        v-hasPermi="[`system:role:edit`]"
        size="middle"
        icon="el-icon-connection"
        :disabled="single"
        @click="handleMenuAndScope()"
      >菜单和数据权限分配</el-button>
      <el-button
        v-hasPermi="[`system:role:allocatedList`]"
        size="middle"
        icon="el-icon-user-solid"
        :disabled="single"
        @click="handleRoleToUser()"
      >角色分配用户</el-button>
      <el-button v-hasPermi="[`system:role:changeStatus`]" size="middle" :icon="disabledStatus === '1'?'el-icon-star-on':'el-icon-star-off'" :disabled="single" @click="handleStatusChange">
        {{ disabledContent }}
      </el-button>
      <el-button v-hasPermi="[`system:role:export`]" size="middle" icon="el-icon-download" @click="educeTable">
        导出
      </el-button>
    </div>
    <!-- 表格展示start -->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="tableData"
      stripe
      :row-style="rowClass"
      class="table-list"
      :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
        (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      @row-click="rowChecked"
    >
      <el-table-column type="selection" width="38" align="center" />
      <el-table-column type="index" label="序号" width="51" align="center" />
      <el-table-column v-if="checkedData[0].checked" prop="roleName" label="角色名称" align="center" :show-overflow-tooltip="true" />
      <el-table-column v-if="checkedData[1].checked" prop="roleKind" label="角色类型" align="center" :show-overflow-tooltip="true" :formatter="roleKindFormat" />
      <el-table-column v-if="checkedData[2].checked" prop="roleKey" label="权限字符" align="center" :show-overflow-tooltip="true" />
      <el-table-column v-if="checkedData[3].checked" prop="roleSort" label="显示顺序" align="center" />
      <el-table-column v-if="checkedData[4].checked" prop="status" min-width="40" label="状态" align="center" :formatter="statusFormat" />
      <!-- <el-table-column v-if="checkedData[5].checked" prop="createTime" label="创建时间" align="center" :show-overflow-tooltip="true" /> -->
    </el-table>
    <!-- 表格展示end-->
    <!-- 分页-->
    <pagination
      :total="total"
      :page.sync="filters.pageNum"
      :limit.sync="filters.pageSize"
      @pagination="getList"
    />

    <!-- 添加页面start -->
    <addDialog ref="addDialog" :role-kind-options="roleKindOptions" :data-scope-options="dataScopeOptions" />
    <!-- 添加页面end-->
    <!-- 初始化 编辑和添加页面 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" />
  </div>
</template>

<script>
import addDialog from './components/addDialog'
import AddOrUpdate from '@/components/System/Role/RoleMenuDataScope'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { listRole, updateRoleStatus, delRole } from '@/api/system/role'
import { mapGetters, mapState } from 'vuex'
// 按钮组件
import systemBtns from '@/components/Common/Btns/systemBtns'
export default {
  components: { addDialog, AddOrUpdate, systemBtns },
  data() {
    return {
      // 高级设置显示隐藏
      highLevelSet: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 启用/停用显示状态
      disabledStatus: '0',
      disabledContent: '停用',
      // 表格数据选择区
      checkedData: [
        { lebel: '角色名称', value: '角色名称', checked: true },
        { lebel: '角色类型', value: '角色类型', checked: true },
        { lebel: '权限字符', value: '权限字符', checked: true },
        { lebel: '显示顺序', value: '显示顺序', checked: true },
        { lebel: '状态', value: '状态', checked: true },
        { lebel: '创建时间', value: '创建时间', checked: true }
      ],
      tableData: [],
      loading: false,
      // 选中表格对话框的存储的值
      multipleSelection: [],
      // 高亮样式
      selectRow: [],
      // 日期范围
      dateRange: '',
      // 搜索框
      filters: {
        pageNum: 1,
        pageSize: this.fristPageSize,
        roleName: '',
        roleKey: '',
        status: '0'
      },
      // 总条数
      total: 0,
      statusOptions: [],
      // 菜单类型选择
      roleKindOptions: [],
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 数据权限弹出层标题
      title: '',

      // 数据范围选项 1：全部数据权限3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限
      dataScopeOptions: [],
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 默认勾选节点key的值
      checkedKeys: [],

      // 角色选择菜单数据权限标识
      addOrUpdateVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  watch: {
    // 高亮样式
    multipleSelection(data) {
      this.selectRow = []
      if (data.length > 0) {
        data.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
    }
  },
  mounted() {
    this.getList()
    // 角色数据权限
    this.getDicts('role_data_scope').then(response => {
      this.dataScopeOptions = response.data.rows
    })
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = [{ dictValue: '', dictLabel: '全部' }, ...response.data.rows]
    })
    this.getDicts('role_type').then(response => {
      this.roleKindOptions = response.data.rows
    })
  },
  methods: {
    getList() {
      this.loading = true
      listRole(this.changeDateRange(this.filters, this.dateRange)).then(resp => {
        this.loading = false
        if (resp) {
          this.tableData = resp.data.rows
          this.total = resp.data.total
          // this.addTaleData()
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // list表格填充空白行
    addTaleData() {
      const arr = {}
      if (this.tableData.length < this.filters.pageSize) {
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }
      this.multipleSelection = val
      // eslint-disable-next-line no-prototype-builtins
      if (this.multipleSelection.length === 1 && this.multipleSelection[0].hasOwnProperty('roleId')) {
        this.single = false
        this.disabledStatus = this.multipleSelection[0].status
        this.disabledContent = this.disabledStatus === '0' ? '停用' : '启用'
      } else {
        this.single = true
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // 获取高级设置中子组件传递的数据
    getValueFromChild(data) {
      this.highLevelQueryParams = data
    },
    // 角色类型字典翻译
    roleKindFormat(row, column) {
      return this.selectDictLabel(this.roleKindOptions, row.roleKind)
    },
    // 导出按钮功能
    educeTable() {
      const wb = XLSX.utils.table_to_book(document.querySelector('.table-list'))
      /* get binary string as output */
      const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '数据表格.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') { console.log(e, wbout) }
      }
      return wbout
    },
    // 用户状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + row.roleName + '角色吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.status === '0') {
            row.status = '1'
          } else {
            row.status = '0'
          }
          const formdata = {
            'roleId': row.roleId,
            'status': row.status
          }
          updateRoleStatus(formdata).then(res => {
            if (res) {
              this.getList()
              this.msgSuccess('操作成功！')
            }
          })
        })
        .catch((error) => {
          console.log(error.message)
        })
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 搜索方法
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.filters.pageNum = 1
      this.dateRange = []
      this.getList()
    },
    // 新增方法
    handleAdd() {
      // 校验当前用户是总公司还是分公司
      const roleKind = this.checkedRoleKind()
      this.$refs.addDialog.handleAdd('新增角色', undefined, roleKind)
    },
    // 编辑
    handleUpdate() {
      const id = this.multipleSelection[0].roleId
      this.$refs.addDialog.handleAdd('修改角色', id)
    },
    // 判读选择的角色类型，总公司填写总公司普通用户，分公司填写分公司普通用户
    checkedRoleKind() {
      const userInfo = this.userInfo
      if (userInfo.enterpriseId === userInfo.subCompany) {
        return '1'
      } else if (userInfo.enterpriseId !== userInfo.subCompany) {
        return '3'
      }
    },
    // 删除操作
    handleDelete() {
      // 获取选中行的id
      const child = this.multipleSelection
      if (child.length === 0) {
        this.msgInfo('请选择需要修改的项!')
      } else {
        this.$confirm('确认要删除角色吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            this.loading = true
            let ids = ''
            for (let i = 0; i < child.length; i++) {
              ids += child[i].roleId + ','
            }
            // 去掉最后一个逗号
            if (ids.length > 0) {
              ids = ids.substr(0, ids.length - 1)
            }
            delRole(ids).then(resp => {
              this.loading = false
              if (resp) {
                this.msgSuccess('删除成功!')
                // 重新加载表格数据
                this.getList()
              } else {
                this.msgError(resp.message)
              }
            })
          })
          .catch(() => {})
      }
    },

    /** 分配菜单和数据权限的弹框 start*/
    handleMenuAndScope() {
      // 获取选中行的id
      const child = this.multipleSelection
      if (child.length === 0) {
        this.msgInfo('请选择需要修改的项!')
      } else if (child.length > 1) {
        this.msgInfo('只能选择一项修改')
      } else {
        this.addOrUpdateVisible = true
        const roleId = child[0].roleId
        this.$nextTick(() => {
          this.$refs.addOrUpdate.showView(roleId)
        })
      }
    },

    /** 角色分配用户 start */
    handleRoleToUser() {
      const child = this.multipleSelection
      const { roleId, roleName } = child[0]
      this.$router.push({
        path: '/system/roleUser',
        name: '角色用户',
        query: { roleId, roleName }
      })
    }
  }
}
</script>
